#include <iostream>
#include <vector>
#include <semaphore.h>
#include <pthread.h>

#define NUM 5

template <class T>
class RingQueue
{
private:
    std::vector<T> ring_queue; // 环形队列
    int _capacity;             // 环形队列的容量
    int c_step;                // 消费者在环形队列下标
    int p_step;                // 生产者在环形队列下标

    pthread_mutex_t _c_mutex; //  消费者互斥锁
    pthread_mutex_t _p_mutex; //  生产者互斥锁

    sem_t cdata_sem_;  // 消费者信号量，消费者关注的数据资源
    sem_t pspace_sem_; // 生产者信号量，生产者关注的空间资源
private:
    void P(sem_t &sem)
    {
        sem_wait(&sem);
    }
    void V(sem_t &sem)
    {
        sem_post(&sem);
    }
    void Lock(pthread_mutex_t &mutex)
    {
        pthread_mutex_lock(&mutex);
    }
    void Unlock(pthread_mutex_t &mutex)
    {
        pthread_mutex_unlock(&mutex);
    }

public:
    //初始化锁和信号量
    RingQueue(int cap = NUM)
        : _capacity(cap), c_step(0), p_step(0), ring_queue(cap)
    {
        sem_init(&cdata_sem_, 0, 0);
        sem_init(&pspace_sem_, 0, cap);

        pthread_mutex_init(&_c_mutex, nullptr);
        pthread_mutex_init(&_p_mutex, nullptr);
    }

    //销毁锁和信号量
    ~RingQueue()
    {
        sem_destroy(&cdata_sem_);
        sem_destroy(&pspace_sem_);

        pthread_mutex_destroy(&_c_mutex);
        pthread_mutex_destroy(&_p_mutex);
    }

    // 生产者发送数据
    void push(const T &in)
    {
        P(pspace_sem_);

        Lock(_p_mutex);

        ring_queue[p_step++] = in;

        p_step %= _capacity; // 因为是循环队列,不能超过队列的容量

        Unlock(_p_mutex);

        V(cdata_sem_);
    }

    // 消费者接受数据
    void pop(T *out)
    {
        P(cdata_sem_);

        Lock(_c_mutex);

        *out = ring_queue[c_step++];
        c_step %= _capacity;
        Unlock(_c_mutex);

        V(pspace_sem_);
    }
};